package com.br.betelgeuse.bean.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.br.betelgeuse.bean.UsuarioInternoBean;

@WebFilter(filterName = "NavigatorPerfilFilter", urlPatterns = "/*")
public class NavigatorPerfilFilter implements Filter {
	// instancia objeto logger
	static Logger logger = Logger.getLogger(NavigatorPerfilFilter.class
			.getName());

	public NavigatorPerfilFilter() {
		// TODO Auto-generated constructor stub
	}

	public void init(FilterConfig arg0) throws ServletException {

	}

	@SuppressWarnings("static-access")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		UsuarioInternoBean session = (UsuarioInternoBean) req.getSession()
				.getAttribute("usuarioInternoBean");
		this.logger.info("Carregando informacoes da sessao.");

		if (((req.getRequestURI().indexOf("alterar_usuarios.jsf") >= 0
				|| req.getRequestURI().indexOf("cadastrar_usuarios.jsf") >= 0
				|| req.getRequestURI().indexOf("painel.jsf") >= 0
				|| req.getRequestURI().indexOf("gerar_selecao.jsf") >= 0 || req
				.getRequestURI().indexOf("listar_selecao.jsf") >= 0) && !session
				.getUsuarioInterno().getPerfil().equals("admin"))) {
			this.logger.info("Usuario "
					+ session.getUsuarioInterno().getUsuario()
					+ " entrando com perfil atendente.");
			resp.sendRedirect(req.getServletContext().getContextPath()
					+ "/modulos/painelAtendente.jsf");
		} else {
			chain.doFilter(request, response);
			this.logger.info("Usuario "
					+ session.getUsuarioInterno().getUsuario()
					+ " entrando com perfil administrador.");
		}

	}

	public void destroy() {

	}

}
